import json
from http.server import HTTPServer, BaseHTTPRequestHandler


class HttpServer:
    host = ('localhost', 8008)
    def __init__(self):
        self.server = HTTPServer(self.host, ResquestHandler)


    def start(self):
        self.server.serve_forever()


class ResquestHandler(BaseHTTPRequestHandler):

    ACITON = None

    # def end_headers(self):
    #     self.send_header('Access-Control-Allow-Origin', '*')
    #     self.send_header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
    #     self.send_header('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type')
    #     BaseHTTPRequestHandler.end_headers(self)

    def do_OPTIONS(self):
        self.send_response(200)
        self.send_header('Content-type', 'text/plain')
        self.send_header('Access-Control-Allow-Origin', '*')
        self.send_header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
        self.send_header('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type')
        self.end_headers()

        # Respond with an empty body to the pre-flight request
        self.wfile.write(b'')

    def do_GET(self):

        self.send_response(200)
        self.send_header('Content-type', 'application/json')
        self.send_header('Access-Control-Allow-Origin', '*')
        self.send_header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
        self.send_header('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type')
        self.end_headers()



        route =  self.parseRoute(self.path)
        params = self.parseParams(self.path)

        if ResquestHandler.ACITON  is not None:
            ResquestHandler.ACITON(route,params,self)

        #self.wfile.write(json.dumps({}).encode())

    def do_POST(self):
        datas = self.rfile.read(int(self.headers['content-length']))

        print('headers', self.headers)
        print("do post:", self.path, self.client_address, datas)

        self.send_response(400)
        self.send_header('Content-type', 'application/json')
        self.send_header('Access-Control-Allow-Origin', '*')
        self.send_header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
        self.send_header('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type')
        self.end_headers()
        self.wfile.write(json.dumps({}).encode())

    def parseRoute(self,route):
        if route.find("?") == -1:
            return  route[1:]
        else:
            return route.split("?")[0][1:]

    def parseParams(self,route):
        if route.find("?") == -1:
            return ""
        else:
            return route.split("?")[1]
